package fina2.dcs.security;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;


import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;

@Stateless
@Scope(ScopeType.SESSION)
@Name("permSession")
@LocalBinding(jndiBinding = "PermissionSession/local")
@AutoCreate
@SuppressWarnings("serial")
public class PermissionSession implements PermissionLocal,Serializable {
	@PersistenceContext
	private EntityManager em;

	@EJB
	private SysStringLocal sysLocal;

	private List<Permission> allPerms = new ArrayList<Permission>();
	
	
	private Logger log=Logger.getLogger(getClass());

	

	public PermissionSession() {
		try {
			
	/*		permComp = new Comparator<Permission>() {
				public int compare(Permission p1, Permission p2) {
					if (p1.getPermValue() == null)
						p1.setPermValue(" ");
					if (p2.getPermValue() == null)
						p2.setPermValue(" ");
					return p1.getPermValue().compareTo(p2.getPermValue());
				}
			};*/
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public Permission findById(BigDecimal id) {
		return em.find(Permission.class, id);
	}

	public void init() {
		log.info("Loading permissions...");
		allPerms = em.createQuery("FROM " + Permission.class.getName() + " p").getResultList();
		List<BigDecimal> ids = new ArrayList<BigDecimal>();

		if (allPerms != null) {
			for (int i = 0; i < allPerms.size(); i++) {
				ids.add(allPerms.get(i).getNameStrId());
			}
			StringBuffer sb = new StringBuffer(ids.toString());
			sb.replace(0, 1, "");
			sb.replace(sb.toString().length() - 1, sb.toString().length(), "");

			List<SysString> permValues = sysLocal.getAllValues(sb.toString(), LanguageSession.langId);

			for (int i = 0; i < allPerms.size(); i++)
				for (int j = 0; j < permValues.size(); j++) {
					if (allPerms.get(i).getNameStrId().equals(permValues.get(j).getPk().getId())) {
						allPerms.get(i).setPermValue(permValues.get(j).getValue());
						break;
					}
				}

			//Collections.sort(allPerms, permComp);
		}
	}

	public List<Permission> getAllPerms() {
		return allPerms;
	}

	public void setAllPerms(List<Permission> allPerms) {
		this.allPerms = allPerms;
	}

	@Remove
	public void remove() {

	}

}
